<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: functions.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * General functions for the Fusion Registry.
 *
 * @package Fusion Registry
 * @subpackage lib
 * @version $Id: functions.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

if ( ! defined( 'IN_IPB' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
    exit();
}

/**#@+
 * Fusion Registry requires
 */
require_once( ROOT_PATH.'sources/lib/func_msg.php' );
require_once( REGISTRY_PATH.'lib/custom_fields.php' );
/**#@-*/

/**
 * Class 'registry_functions' contains general functions for the Fusion Registry.
 *
 * Functions in this class are either used throughout the entire program,
 * or don't specifically belong to a particular class. <b>NOTE:</b> This class
 * requires that a {@link custom_fields} object be initialized, it will look
 * by default in the parent class array $lib['custom_fields'] for an existing
 * object, if none found it will create one.
 *
 * @package Fusion Registry
 * @subpackage lib
 */
class registry_functions
{
    /**#@+ @var object */
    var $ipsclass;
    var $class  = "";
    var $msg_lib = "";
    /**#@-*/

    /** @var string */
    var $output = "";

    /**
     * Constructor, nothing too special here
     *
     * @param object $class Our parent class object
     * @return boolean TRUE
     */
    function auto_run($class)
    {
        $this->class = &$class;

        // Initialize support classes
        $this->msg_lib = new func_msg();
        $this->msg_lib->ipsclass =& $this->ipsclass;

        // Initialize custom_fields if it isn't already
        if ( !is_object( $this->class->lib['custom_fields'] ) )
        {
            $this->class->lib['custom_fields'] = new registry_custom_fields(&$class);
            $this->class->lib['custom_fields']->ipsclass =& $this->ipsclass;
        }

        return TRUE;
    }
    

    /**
     * Builds the HTML for the categories select
     *
     * Usage:  build_category_html( array( 'selected' => <category_id> ) );
     *
     * @param array $data
     * @return string HTML source for the categories select list
     */
    function build_category_html($data = array())
    {
        // Build the category select HTML
        $categories_html = '<select name="category" class="forminput">';

        $this->ipsclass->DB->query("SELECT * FROM ibf_registry_categories ORDER BY title ASC");
        while ( $cat_row = $this->ipsclass->DB->fetch_row() )
        {
            if ( $cat_row['id'] == $data['selected'] )
            {
                $categories_html .= '<option value="'.$cat_row['id'].'" selected="selected">'.$cat_row['title'].'</option>';
            }
            else
            {
                $categories_html .= '<option value="'.$cat_row['id'].'">'.$cat_row['title'].'</option>';
            }
        }

        // Finish off the category select HTML        
        $categories_html .= '</select>';

        return $categories_html;
    }


    /**
     * Builds the HTML for the ratings select
     *
     * Usage:  build_rating_html( array( 'START' => <start rating, high value>, 'END' => <end rating, low value>, 'selected' => <selected rating>, ) );
     *
     * @param array $data
     * @return string HTML source for the rating list
     */
    function build_rating_html($data = array())
    {
        // A simple check to prevent infinite loop
        if ( $data['START'] < $data['END'] )
        {
            return '';
        }    

        $rating_html = "<select name='rating' class='forminput'>";

        for ( $rating = $data['START']; $rating >= $data['END']; $rating-- )
        {
            if ( $rating == $data['selected'] )
            {
                $rating_html .= "<option value='$rating' selected='selected'>$rating</option>";
            }
            else
            {
                $rating_html .= "<option value='$rating'>$rating</option>";
            }
        }

        $rating_html .= "</select>";

        return $rating_html;
    }


    /**
     * Create our vehicle make/model javascript
     *
     * @return string Javascript source defining all Makes & Models
     */
    function build_vehicle_javascript()
    {
        // We are forming this type of javascript output:
        //   cars["Acura"] = new Array("7", new Array("CL","TL"), new Array("10","11"));
        //
        // This represents:
        //   cars["Make"] = new Array("make_id", new Array("Model A","Model B"), new Array("Model_A_id","Model_B_id"));

        $return = '';

        $make_q_id = $this->ipsclass->DB->query("SELECT id, make FROM ibf_registry_makes ORDER BY make ASC");

        // Loop through all the makes
        while ( $make_row = $this->ipsclass->DB->fetch_row($make_q_id) )
        {
            // Start this makes' row in the output, this is where it gets confusing!
            $return .= 'cars["'.$make_row['make'].'"] = new Array("'.$make_row['id'].'", new Array(';

            $model_q_id = $this->ipsclass->DB->query("SELECT id, model FROM ibf_registry_models 
                                                      WHERE make_id='".$make_row['id']."' ORDER BY model ASC");

            $model_string = '';
            $model_id_string = '';

            // Loop through all the models of this make
            while ( $model_row = $this->ipsclass->DB->fetch_row($model_q_id) )
            {
                // Create the arrays that we will use in the output
                $model_string    .= '"'.$model_row['model'].'",';
                $model_id_string .= '"'.$model_row['id']   .'",';
            }

            // Strip off the last comma
            $model_string    = substr($model_string,    0, -1);
            $model_id_string = substr($model_id_string, 0, -1);

            // Finish off this makes' row in the output
            $return .= $model_string ."), new Array(". $model_id_string ."));\n";
        }

        return $return;
    }


    /**
     * Build the latest updated HTML
     *
     * @return string|null Template 'latest_updated' or null
     */
    function do_latest_updated()
    {
        // Make sure it's enabled
        if ( $this->class->registry_config['tmpl_lastupdateditemsmain_on'] != 1 )
        {
            return '';
        }

        $latest_updated_num = ( empty( $this->class->registry_config['tmpl_lastupdateditemsmain_limit'] ) ) 
                              ? 5 
                              : $this->class->registry_config['tmpl_lastupdateditemsmain_limit'];

        // Get our fields that are going to be displayed
        $cf_highlight = $this->class->lib['custom_fields']->get_cf_highlight();

        // Create our sql id list, this will be used when retrieving the custom field entries.
        $cf_ids = "'". implode( "','", array_keys($cf_highlight) ) . "'";
                              
        // Get data
        $query = $this->ipsclass->DB->query( "SELECT g.id, g.member_id, g.date_updated, m.members_display_name 
                                              FROM ( ibf_registry_items AS g, ibf_members AS m ) 
                                              WHERE g.member_id = m.id
                                              ORDER BY g.date_updated DESC LIMIT 0,".$latest_updated_num);

        $list = '';
        while ( $row = $this->ipsclass->DB->fetch_row($query) )
        {
            // Get the specific highlight field values for each entry.
            $cf_entries = $this->class->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$row['id']."' AND field_id IN (".$cf_ids.")" ) );

            // Process the highlight field values
            $row['highlight_fields'] = '';

            foreach ( $cf_highlight as $cf_id => $cf_row )
            {
                $row['highlight_fields'] .= $this->class->lib['custom_fields']->process_cf_value( array( 'def' => $cf_row, 'value' => $cf_entries[$cf_id]['field_value'], 'type' => 'view' ) );
                
                $row['highlight_fields'] .= ' ';
            }

            $row['highlight_fields'] = substr($row['highlight_fields'], 0 ,-1);

            $row['date_updated'] = $this->ipsclass->get_date( $row['date_updated'], 'LONG' );

            $list .= $this->ipsclass->compiled_templates['skin_registry_core']->latest_updated_row($row);
        }

        return $this->ipsclass->compiled_templates['skin_registry_core']->latest_updated($list);
    }


    /**
     * Build the 'My Items' HTML
     *
     * @todo Implement session based cache of items and custom highlight fields
     * @return string Template 'my_items' or empty value
     */
    function do_my_items()
    {
        // Get our fields that are going to be displayed
        $cf_highlight = $this->class->lib['custom_fields']->get_cf_highlight();
        
        // Create our sql id list, this will be used when retrieving the custom field entries.
        $cf_ids = "'". implode( "','", array_keys($cf_highlight) ) . "'";

        $show_add = 0;

        if ( !empty( $this->ipsclass->member['id'] ) )
        {
            $list = '';

            // Make sure they haven't exceeded the max item limit
            $this->ipsclass->DB->query("SELECT count(*) AS total_cars FROM ibf_registry_items WHERE member_id = '". $this->ipsclass->member['id'] ."'");
            $row = $this->ipsclass->DB->fetch_row();

            if ($row['total_cars'] < $this->class->registry_config['max_user_cars'])
            {
                // Add the menu item if they still can add more items
                $show_add = 1;
            }

            // Get data
            $query = $this->ipsclass->DB->query( "SELECT id FROM ibf_registry_items WHERE member_id = '". $this->ipsclass->member['id'] ."' ORDER BY id ASC" );

            while ( $row = $this->ipsclass->DB->fetch_row($query) )
            {
                // Get the specific highlight field values for each entry.
                $cf_entries = $this->class->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$row['id']."' AND field_id IN (".$cf_ids.")" ) );

                // Process the highlight field values
                $row['highlight_fields'] = '';

                foreach ( $cf_highlight as $cf_id => $cf_row )
                {
                    $row['highlight_fields'] .= $this->class->lib['custom_fields']->process_cf_value( array( 'def' => $cf_row, 'value' => $cf_entries[$cf_id]['field_value'], 'type' => 'view' ) );
                    
                    $row['highlight_fields'] .= ' ';
                }

                $row['highlight_fields'] = substr($row['highlight_fields'], 0 ,-1);

                $list .= $this->ipsclass->compiled_templates['skin_registry_core']->my_items_row($row);
            }

            return $this->ipsclass->compiled_templates['skin_registry_core']->my_items($list, $show_add);
        }
        else
        {
            return '';
        }
    }


    /**
     * Build the side bar navigation for members or guests
     *
     * This function used to have logic, this has been moved into the template
     * code to reduce code, and to combine two template bits into one.
     *
     * @return string Template 'navigation'
     */
    function do_navigation()
    {
        return $this->ipsclass->compiled_templates['skin_registry_core']->navigation();
    }


    /**
     * Send a PM
     *
     * @param array $data Array with keys 'to', 'subject', and 'post'
     * @return boolean TRUE|FALSE
     */
    function send_msg( $data=array() )
    {
        // If we don't have goods, error out
        if ( empty($data['to']) OR empty($data['subject']) OR empty($data['post']) )
        {
            return FALSE;
        }
         
        $this->msg_lib->init();
        $this->msg_lib->register_class( &$this );

        // Setup the PM details, To: (username not id)
        $this->msg_lib->to          = $data['to'];
        $this->msg_lib->from_member = $this->ipsclass->member;
        $this->msg_lib->msg_title   = $data['subject'];
        $this->msg_lib->msg_post    = $data['post'];

        // Send it!
        $this->msg_lib->send_pm();

        return TRUE;
    }

}

?>